package com.kaibes.module.value;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaibes.core.base.util.StringUtils;
import com.kaibes.orm.curd.QueryBuilder;
import com.kaibes.web.api.ResponseServiceImpl;

@Service
public class KeyValueService extends ResponseServiceImpl<KeyValue> {

    @Autowired
    private ObjectMapper objectMapper;

    public int update(KeyValue keyValue) {
        return super.update(keyValue, QueryBuilder.newBuilder().eq("key", keyValue.getKey()).build());
    }

    public KeyValue getByKey(String key) {
        return get(QueryBuilder.newBuilder().eq("key", key).build());
    }

    public String getValueByKey(String key) {
        KeyValue keyValue = get(QueryBuilder.newBuilder().eq("key", key).build(), "value");
        return keyValue == null ? "" : keyValue.getValue();
    }
    
    public boolean saveObject(String key, Object object) {
    	try {
            String value = objectMapper.writeValueAsString(object);
            KeyValue keyValue = getByKey(key);
            if (keyValue == null) {
                keyValue = new KeyValue();
                keyValue.setKey(key);
                keyValue.setValue(value);
                return save(keyValue)!=null;
            } else {
                keyValue.setValue(value);
                return update(keyValue) > 0;
            }
        } catch (JsonProcessingException e) {
            return false;
        }
    }

    public boolean saveObject(Object object) {
        return saveObject(object.getClass().getName(), object);
    }
    
    public <T> T getObject(Class<T> clazz) {
        String key = clazz.getName();
        KeyValue keyValue = getByKey(key);
        if (keyValue == null) {
            return null;
        }
        
        String value = keyValue.getValue();
        try {
            return StringUtils.isBlank(value) ? null : objectMapper.readValue(value, clazz);
        } catch (JsonProcessingException e1) {
            return null;
        }
    }

}
